1. Implicit Route Model Binding
// Define a route with implicit model binding
Route::get('user/{user}', [UserController::class, 'show'])->name('user.show');
// In UserController
public function show(User $user)
{
return view('user.show', compact('user'));
}
Route::get('user/{user}', [UserController::class, 'show']) automatically resolves the User model for the {user} parameter using its primary key.Route Definition:
Laravel injects the User model instance directly into the show method, simplifying code and avoiding manual query logic.Controller Method:
2. Explicit Route Model Binding
// Define a route with explicit model binding
Route::get('post/{post}', [PostController::class, 'show'])->name('post.show');
// In AppServiceProvider
public function boot()
{
parent::boot();
Route::bind('post', function ($value) {
return Post::where('slug', $value)->firstOrFail();
});
}
// In PostController
public function show(Post $post)
{
return view('post.show', compact('post'));
}
Route::get('post/{post}', [PostController::class, 'show']) uses explicit binding to handle custom retrieval logic.Route Definition:
In AppServiceProvider, Route::bind('post', function ($value) { ... }) allows you to define how the model should be resolved, such as using a non-primary key (e.g., slug).Custom Binding Logic:
Laravel injects the Post model instance, resolved by the custom logic, into the show method.Controller Method:
Difference
Automatically resolves models based on route parameters and primary keys, making code cleaner and easier to maintain.Implicit Binding:
Allows custom logic for model retrieval, offering more flexibility in how models are resolved.Explicit Binding:
You Might Also Like
Cache Blade Views for Faster Rendering
Cache rendered Blade views to store compiled templates and reduce server processing time. Laravel's...
Use HTTPS for Secure Communication
Ensure your application uses HTTPS to encrypt data transmitted between the client and server. Update...